/**************************************************************************************** 
 Copyright © 2003-2012 hbasesoft Corporation. All rights reserved. Reproduction or       <br>
 transmission in whole or in part, in any form or by any means, electronic, mechanical <br>
 or otherwise, is prohibited without the prior written consent of the copyright owner. <br>
 ****************************************************************************************/
package com.hbasesoft.hamibot.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.hbasesoft.framework.common.GlobalConstants;
import com.hbasesoft.framework.common.ServiceException;
import com.hbasesoft.framework.common.utils.date.DateUtil;
import com.hbasesoft.framework.db.core.utils.PagerList;
import com.hbasesoft.hamibot.Cmd;
import com.hbasesoft.hamibot.dao.AppLogDao;
import com.hbasesoft.hamibot.entity.AppLogEntity;

import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * <Description> <br>
 * 
 * @author 王伟<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2024年12月24日 <br>
 * @since V1.0<br>
 * @see com.hbasesoft.hamibot.controller <br>
 */
@RestController
@RequestMapping("/api/log")
public class AppLogController {

    /** */
    private static final String FILE_STORAGE_PATH = GlobalConstants.FILE_STORAGE_PATH + "/hamibot";

    /** */
    private static final int MAX_PAGE_SIZE = 50;

    @Resource
    private AppLogDao appLogDao;

    /**
     * Description: 查询 <br>
     * 
     * @author 王伟<br>
     * @taskId <br>
     * @return <br>
     */
    @Transactional(readOnly = true)
    @GetMapping
    public Map<String, Object> query(final @RequestParam(value = "current", required = false) Integer current,
        final @RequestParam(value = "pageSize", required = false) Integer pageSize,
        final @RequestParam(value = "deviceId", required = false) String deviceId,
        final @RequestParam(value = "direction", required = false) Integer direction) {
        Integer pageIndex = current;
        if (pageIndex == null) {
            pageIndex = 1;
        }

        PagerList<AppLogEntity> data = appLogDao
            .queryPagerByLambda(q -> q.eq(direction != null, AppLogEntity::getDirection, direction)
                .eq(StringUtils.isNotEmpty(deviceId), AppLogEntity::getDeviceId, deviceId)
                .greaterThan(AppLogEntity::getCreateTime, DateUtil.offset(DateUtil.HOUR, -1))
                .orderByDesc(AppLogEntity::getId), pageIndex, pageSize == null ? MAX_PAGE_SIZE : pageSize);

        Map<Integer, String> map = Cmd.toMap();
        for (AppLogEntity appLog : data) {
            if (appLog.getCmd() != null) {
                appLog.setCmdInfo(map.get(appLog.getCmd()));
            }
        }

        Map<String, Object> resp = new HashMap<>();
        resp.put("data", data);
        resp.put("page", data.getPageIndex());
        resp.put("total", data.getTotalCount());
        return resp;
    }

    /**
     * Description: <br>
     * 
     * @author 王伟<br>
     * @taskId <br>
     * @param request
     * @param response <br>
     */
    @GetMapping("/download/**")
    public void download(final HttpServletRequest request, final HttpServletResponse response) {
        String uri = request.getRequestURI();
        String filePath = uri.substring("/api/log/download".length(), uri.length());

        response.setContentType("image/png");
        try {

            response.setHeader("Accept-Ranges", "bytes");
            File file = new File(FILE_STORAGE_PATH + filePath);
            response.setContentLength(Long.valueOf(file.length()).intValue());
            if (file.exists()) {
                try (InputStream in = new FileInputStream(file)) {
                    IOUtils.copy(in, response.getOutputStream());
                }
            }
        }
        catch (Exception e) {
            throw new ServiceException(e);
        }
    }
}
